// https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/?envType=study-plan-v2&envId=top-interview-150

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> index;

    TreeNode* myBuildTree(vector<int> inorder, vector<int> postorder, int inorder_left, int inorder_right, int postorder_left, int postorder_right) {
        if (postorder_left > postorder_right) {
            return nullptr;
        }

        int postorder_root = postorder_right;
        int inorder_root = index[postorder[postorder_root]];

        TreeNode* root = new TreeNode(postorder[postorder_root]);

        int rightTreeLen = inorder_right - inorder_root;
        root->right = myBuildTree(inorder, postorder, inorder_root + 1, inorder_right, postorder_right - rightTreeLen, postorder_right - 1);
        root->left = myBuildTree(inorder, postorder, inorder_left, inorder_root  - 1, postorder_left, postorder_right - rightTreeLen - 1);

        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size();
        for (int i = 0; i < n; i++) {
            index[inorder[i]] = i;
        }
        return myBuildTree(inorder, postorder, 0, n - 1, 0, n - 1);
    }
};